package com.example.fourtestapp.ui;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.fourtestapp.MainActivity;
import com.example.fourtestapp.R;
import com.example.fourtestapp.entity.UserInfo;
import com.example.fourtestapp.utils.Config;
import com.example.fourtestapp.utils.HttpUtils;
import com.example.fourtestapp.utils.RegUtils;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private EditText name;
    private EditText pwd;
    private CheckBox checkbox1;
    private CheckBox checkbox2;
    private Button ipset, login,regist;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private UserInfo userInfo = new UserInfo();
    private ProgressDialog progressDialog;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    String ip = sharedPreferences.getString("ip", "");
                    String port = sharedPreferences.getString("port", "");
                    Config.URL = "http://" + ip + ":" + port;
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    login.setEnabled(true);
                    overridePendingTransition(R.anim.anim_test_in, R.anim.anim_test_out);
                    finish();
                    break;
                case 500:
                    Toast.makeText(LoginActivity.this, msg.obj.toString() + "", Toast.LENGTH_SHORT).show();
                    login.setEnabled(true);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        initCheck();
        initListeren();
    }

    //自动登录
    private void initCheck() {
        String save = sharedPreferences.getString("save", "");
        if ("1".equals(save)) {
            name.setText(sharedPreferences.getString("name", ""));
            pwd.setText(sharedPreferences.getString("pwd", ""));
            checkbox1.setChecked(true);
        }
        String autologin = sharedPreferences.getString("autologin", "");
        if ("2".equals(autologin) && Checkip()) {
            progressDialog = ProgressDialog.show(LoginActivity.this,
                    "提示", "正在自动登录中", true, false);
            progressDialog.show();
            handler.postDelayed(runnable, 200);
        }
    }
    //子线程登录
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                Loginin();
                login.setEnabled(false);
                Thread.sleep(1500);
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
                login.setEnabled(true);
            } catch (Exception e) {
            }

        }
    };
    //初始化
    private void initView() {
        name = findViewById(R.id.name);
        pwd = findViewById(R.id.pwd);
        checkbox1 = findViewById(R.id.checkbox1);
        checkbox2 = findViewById(R.id.checkbox2);
        ipset = findViewById(R.id.ipset);
        login = findViewById(R.id.login);
        regist = findViewById(R.id.regist);
        sharedPreferences = LoginActivity.this.getSharedPreferences("user", 0);
        editor = sharedPreferences.edit();
    }

    //检测网络设置
    private void Loginin() {
        final String names = name.getText().toString();
        final String pwds = pwd.getText().toString();
        if (Checkip()) {
            if (checkbox1.isChecked()) {
                editor.putString("save", "1");
                editor.putString("name", names);
                editor.putString("pwd", pwds);
                editor.commit();
            } else {
                editor.putString("save", "");
                editor.commit();
            }
            if (checkbox2.isChecked()) {
                editor.putString("autologin", "2");
                editor.commit();
            } else {
                editor.putString("autologin", "");
                editor.commit();
            }
            String url = "http://liushenlong.cn/api/user?name=" + names + "&pwd=" + pwds;
            HttpUtils.Get(url, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    Toast.makeText(LoginActivity.this, "请求超时"+e.getMessage(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String data = response.body().string();
                    userInfo = new Gson().fromJson(data, UserInfo.class);
                    Message message = new Message();
                    message.what = userInfo.getCode();
                    message.obj = userInfo.getMsg();
                    handler.sendMessage(message);
                }
            });
        } else {
            Toast.makeText(LoginActivity.this, "请先设置网络", Toast.LENGTH_SHORT).show();
        }

    }

    //监听事件
    private void initListeren() {
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login.setEnabled(false);
                Loginin();
                login.setEnabled(true);
            }
        });

        ipset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final View dv = LayoutInflater.from(LoginActivity.this).inflate(R.layout.dig_ipset, null);
                final AlertDialog dialog = new AlertDialog
                        .Builder(LoginActivity.this)
                        .setTitle("网络设置")
                        .setView(dv)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                EditText ip = dv.findViewById(R.id.ip);
                                EditText port = dv.findViewById(R.id.port);
                                String ips = ip.getText().toString();
                                String ports = port.getText().toString();
                                if (RegUtils.Check(ips)) {
                                    editor.putString("ip", ips);
                                    editor.putString("port", ports);
                                    editor.commit();
                                    Toast.makeText(LoginActivity.this, "网络设置成功！", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(LoginActivity.this, "检查到ip地址或端口输入不正确！", Toast.LENGTH_SHORT).show();
                                    Toast.makeText(LoginActivity.this, "请重新输入", Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .setNegativeButton("取消", null).create();
                EditText ip = dv.findViewById(R.id.ip);
                EditText port = dv.findViewById(R.id.port);
                String loadip = sharedPreferences.getString("ip", "");
                String loadport = sharedPreferences.getString("port", "");
                if (!"".equals(loadip) || !"".equals(loadport)) {
                    ip.setText(loadip);
                    port.setText(loadport);
                }
                dialog.show();
            }
        });


        regist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LoginActivity.this, RegistActivity.class));
            }
        });
    }

    //检查本地是否存有网络设置的相关数据
    private Boolean Checkip() {
        String ip = sharedPreferences.getString("ip", "");
        String port = sharedPreferences.getString("port", "");
        if ("".equals(ip) || "".equals(port)) {
            return false;
        } else {
            return true;
        }
    }
}
